package com.hou.eduservice.controller;


import com.hou.commonutils.R;
import com.hou.eduservice.client.VodClient;
import com.hou.eduservice.entity.EduVideo;
import com.hou.eduservice.service.EduVideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2021-10-17
 */
@RestController
@RequestMapping("/eduservice/video")
@CrossOrigin
public class EduVideoController {

    @Autowired
    private EduVideoService videoService;

    @Autowired
    private VodClient vodClient;


    // 添加小节
    @PostMapping("addVideo")
    public R addVideo(@RequestBody EduVideo video) {

        videoService.save(video);

        return R.ok();
    }

    // 根据id查询小节
    @GetMapping("getVideo/{videoId}")
    public R getVideo(@PathVariable String videoId) {

        EduVideo video = videoService.getById(videoId);

        return R.ok().data("video",video);
    }

    // 修改小节
    @PostMapping("updateVideo")
    public R updateVideo(@RequestBody EduVideo video) {
        videoService.updateById(video);
        return R.ok();
    }

    //删除小节，删除对应阿里云视频
    @DeleteMapping("{id}")
    public R deleteVideo(@PathVariable String id) throws Exception {
        //根据小节id获取视频id，调用方法实现视频删除
        EduVideo eduVideo = videoService.getById(id);
        String videoSourceId = eduVideo.getVideoSourceId();
        //判断小节里面是否有视频id
        if(!StringUtils.isEmpty(videoSourceId)) {
            //根据视频id，远程调用实现视频删除
            R res = vodClient.removeAlyVideo(videoSourceId);
            if (!res.getSuccess()){
                throw new Exception("启动熔断器机制，删除视频失败！");
            }
        }
        //删除小节
        videoService.removeById(id);
        return R.ok();
    }


}

